package model;

import com.jfinal.i18n.Res;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;
import result.Result;

import java.util.List;

public class User extends Model<User> {
    public static  User me = new User();

    public Result isPermitted(String username, String password){
        Record record=Db.findFirst("select username,password,user_type " +
                     "from user " +
                     "where username = '"+username+"' " +
                     "and is_valid = 1");
        if (record == null){
            return Result.layui(0,null);
        }else{
//                return record.get("password").equals(password)?2:1;
            if (record.get("password").equals(password)){
                return "管理员".equals(record.get("user_type"))?
                        Result.layui(2,record):Result.layui(3,record);
            }else{
                return Result.layui(1,record);
            }
        }

    }

    public List<Record> listUsers(Integer start,Integer limit) {
        List<Record> records=Db.find("select id,username,password,user_type,creation_date " +
                     "from user " +
                     "where is_valid = 1 " +
                     "limit "+start+","+limit);
        return records;

    }

    public Integer removeUser(String ids){
     Integer result =  Db.update("update user " +
                     "set is_valid = 0 " +
                     "where id in "+ids);

       return result;
    }


    public  Boolean addUser(Record record){
     boolean result=Db.save("user",record);
     return result;
    }

    public  boolean updateUser(Record record){
      boolean result=  Db.update("user",record);
      return result;
    }


    public Long countUser() {
       Long count = Db.queryLong( "select count(1) " +
                           "from user " +
                           "where is_valid = 1");
       return count;
    }

    public Record selectByUsername(String username) {
       Record record= Db.findFirst("select id  " +
                "from user " +
                "where username='"+username+"' " +
                "and is_valid = 1");
        return record;
    }
}
